package com.nami.gate.middleware.mq.listener;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import com.nami.gate.cache.LocalChannelCache;
import com.nami.gate.cache.TempChannelCache;
import com.nami.gate.constants.ChannelConstants;
import com.nami.gate.external.basic.constants.DownTopicConst;
import com.nami.im.network.model.enums.protocol.CMDEnum;
import com.nami.im.network.model.packet.v2.Packet;
import com.nami.transport.proto.codec.MqTransMsg;
import io.netty.channel.Channel;
import io.netty.util.AttributeKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class DownMsgLoginConsumer extends AbstractConsumer {

    private static final Logger log = LoggerFactory.getLogger(DownMsgLoginConsumer.class);

    @Override
    public void onMessage(byte[] body) {
        try {
            TimeInterval timer = DateUtil.timer();

            MqTransMsg.Logic2GateLoginResponse downMsgBody = MqTransMsg.Logic2GateLoginResponse.parseFrom(body);
//            DownLoginWrap downLoginWrap = JsonUtils.parseObject(body, DownLoginWrap.class);

            Packet downPacket = new Packet();
            downPacket.setMagic((byte) 8);
            downPacket.setCmd(CMDEnum.CONNACK.getCode());
            downPacket.setQos((byte) 0);
            downPacket.setBody(downMsgBody.getDownMsgBody().toByteArray());
            if (downMsgBody.getSuccess()) {
                log.info("[down-login] ws节点开始处理[{}]登录成功消息", downMsgBody.getUserId());
                String tempNo = downMsgBody.getTempFingerprint();
                Channel channel = TempChannelCache.getTempChannel(tempNo);
                if (channel == null) {
                    log.warn("[down-login] tempChannel is null。");
                    TempChannelCache.removeChannel(tempNo);
                    return;
                }
                bindingUserInfoToChannel(channel, downMsgBody);
                LocalChannelCache.put(channel.id().asLongText(), downMsgBody.getSessionId());
                LocalChannelCache.put(downMsgBody.getSessionId(), channel);
                // 删除临时cache
                TempChannelCache.removeChannel(tempNo);

                channel.writeAndFlush(downPacket);
                log.info("[down-login] ws节点向客户端【{}】写入成功. use:{}ms", channel.remoteAddress(), timer.interval());
                return;
            }

            Channel tempChannel = TempChannelCache.getTempChannel(downMsgBody.getTempFingerprint());
            if (tempChannel == null) {
                TempChannelCache.removeChannel(downMsgBody.getTempFingerprint());
                return;
            }
            tempChannel.writeAndFlush(downPacket);
            TempChannelCache.removeChannel(downMsgBody.getTempFingerprint());
//            tempChannel.close(); // 暂时不关闭长连接通道
        } catch (Exception var3) {
            var3.printStackTrace();
            log.error("[down-login] 消费出现问题:{}", var3.getMessage());
        }

    }

    private static void bindingUserInfoToChannel(Channel channel, MqTransMsg.Logic2GateLoginResponse response) {
//        channel.attr(AttributeKey.valueOf(ChannelConstants.USER_TOKEN)).set(response.getToken());
        channel.attr(AttributeKey.valueOf(ChannelConstants.USER_ID)).set(response.getUserId());
        channel.attr(AttributeKey.valueOf(ChannelConstants.APP_KEY)).set(response.getAppKey());
        channel.attr(AttributeKey.valueOf(ChannelConstants.PLATFORM)).set(response.getPlatform());
        channel.attr(AttributeKey.valueOf(ChannelConstants.INSTANCE_ID)).set(response.getInstanceId());
        channel.attr(AttributeKey.valueOf(ChannelConstants.READ_TIME)).set(System.currentTimeMillis());
    }

    @Override
    public String getTopicName() {
        return DownTopicConst.LOGIN_TOPIC;
    }


}


